<template>
  <div class="withdrawal-apply page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">申请提现列表</h1>
        <p class="page-subtitle">管理用户提现申请，处理提现相关事务</p>
      </div>
    </div>

    <div class="content-card">
      <div class="search-section">
        <el-input
          v-model="searchForm.customerId"
          placeholder="用户ID"
          class="search-input"
          clearable
        />
        <el-input
          v-model="searchForm.withdrawalNo"
          placeholder="提现单号"
          class="search-input"
          clearable
        />
        <el-input
          v-model="searchForm.paymentNo"
          placeholder="交易单号"
          class="search-input"
          clearable
        />
        <el-select
          v-model="searchForm.status"
          placeholder="提现状态"
          clearable
          class="status-select"
        >
          <el-option label="待审核" :value="0" />
          <el-option label="审核通过" :value="1" />
          <el-option label="审核拒绝" :value="2" />
          <el-option label="打款中" :value="3" />
          <el-option label="打款成功" :value="4" />
          <el-option label="打款失败" :value="5" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <el-table
        :data="withdrawalList"
        style="width: 100%"
        class="withdrawal-table"
        v-loading="loading"
        row-key="withdrawalNo"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="withdrawalNo"
          label="提现单号"
          width="220"
          show-overflow-tooltip
        />
        <el-table-column
          prop="customerId"
          label="用户ID"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="amount"
          label="提现金额"
          width="120"
          align="right"
        >
          <template #default="{ row }">
            <div class="amount-cell">
              <div class="amount-value">
                {{ formatCurrency(row.amount) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="actualAmount"
          label="到账金额"
          width="120"
          align="right"
        >
          <template #default="{ row }">
            <div class="amount-cell">
              <div class="amount-value actual-amount">
                {{ formatCurrency(row.actualAmount) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="serviceFee"
          label="手续费"
          width="100"
          align="right"
        >
          <template #default="{ row }">
            <div class="amount-cell">
              <div class="amount-value fee-amount">
                {{ formatCurrency(row.serviceFee) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="提现状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="auditRemark"
          label="审核备注"
          width="150"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.auditRemark">{{ row.auditRemark }}</span>
            <span v-else class="no-remark">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="auditorId"
          label="审核人"
          width="100"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.auditorId">{{ row.auditorId }}</span>
            <span v-else class="no-auditor">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdTime"
          label="申请时间"
          width="160"
          show-overflow-tooltip
        />
        <el-table-column
          prop="auditTime"
          label="审核时间"
          width="160"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.auditTime">{{ row.auditTime }}</span>
            <span v-else class="no-audit">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="paymentTime"
          label="打款时间"
          width="160"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.paymentTime">{{ row.paymentTime }}</span>
            <span v-else class="no-payment">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="paymentNo"
          label="交易单号"
          width="200"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.paymentNo">{{ row.paymentNo }}</span>
            <span v-else class="no-payment-no">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="failureReason"
          label="失败原因"
          width="150"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.failureReason">{{ row.failureReason }}</span>
            <span v-else class="no-failure">-</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <!-- 待审核状态：显示审核通过和审核拒绝按钮 -->
              <template v-if="row.status === 0">
                <el-button
                  size="small"
                  type="success"
                  @click="approveWithdrawal(row)"
                  class="action-btn"
                >
                  审核通过
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="rejectWithdrawal(row)"
                  class="action-btn"
                >
                  审核拒绝
                </el-button>
              </template>

              <!-- 审核通过状态：显示打款按钮 -->
              <template v-if="row.status === 1">
                <el-button
                  size="small"
                  type="primary"
                  @click="processPayment(row)"
                  class="action-btn"
                >
                  打款
                </el-button>
              </template>

              <!-- 打款失败状态：显示重新打款按钮 -->
              <template v-if="row.status === 5">
                <el-button
                  size="small"
                  type="warning"
                  @click="retryPayment(row)"
                  class="action-btn"
                >
                  重新打款
                </el-button>
              </template>

              <!-- 其他状态：显示详情按钮 -->
              <template v-if="[2, 3, 4].includes(row.status)">
                <el-button
                  size="small"
                  type="info"
                  @click="viewDetail(row)"
                  class="action-btn"
                >
                  详情
                </el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 审核拒绝对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="审核拒绝"
      width="500px"
      @close="resetRejectForm"
    >
      <el-form :model="rejectForm" label-width="100px">
        <el-form-item label="拒绝原因" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmReject">确定拒绝</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 打款对话框 -->
    <el-dialog
      v-model="paymentDialogVisible"
      title="确认打款"
      width="500px"
      @close="resetPaymentForm"
    >
      <el-form :model="paymentForm" label-width="120px">
        <el-form-item label="提现单号">
          <el-input :value="paymentForm.withdrawalNo" disabled />
        </el-form-item>
        <el-form-item label="提现金额">
          <el-input :value="formatCurrency(paymentForm.amount)" disabled />
        </el-form-item>
        <el-form-item label="交易单号" required>
          <el-input
            v-model="paymentForm.paymentNo"
            placeholder="请输入交易单号"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="paymentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPayment">确定打款</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { postWithAuth } from "@/utils/request";

// 类型定义
interface WithdrawalInfo {
  customerId: string;
  withdrawalNo: string;
  amount: number;
  actualAmount: number;
  serviceFee: number;
  status: number;
  auditRemark: string;
  auditTime: string;
  auditorId: string;
  paymentTime: string;
  paymentNo: string;
  failureReason: string;
  createdTime: string;
}

const loading = ref(false);
const withdrawalList = ref<WithdrawalInfo[]>([]);

// 搜索表单
const searchForm = ref({
  customerId: "",
  withdrawalNo: "",
  paymentNo: "",
  status: "",
});

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 审核拒绝对话框
const rejectDialogVisible = ref(false);
const rejectForm = ref({
  withdrawalNo: "",
  reason: "",
});

// 打款对话框
const paymentDialogVisible = ref(false);
const paymentForm = ref({
  withdrawalNo: "",
  amount: 0,
  paymentNo: "",
});

// 获取状态文本
const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: "待审核",
    1: "审核通过",
    2: "审核拒绝",
    3: "打款中",
    4: "打款成功",
    5: "打款失败",
  };
  return statusMap[status] || "未知状态";
};

// 获取状态标签类型
const getStatusTagType = (status: number): string => {
  const typeMap: Record<number, string> = {
    0: "warning", // 待审核
    1: "success", // 审核通过
    2: "danger", // 审核拒绝
    3: "primary", // 打款中
    4: "success", // 打款成功
    5: "danger", // 打款失败
  };
  return typeMap[status] || "info";
};

// 格式化金额
const formatCurrency = (amount: number | null): string => {
  if (amount === null || amount === undefined) return "-";
  const num = Number(amount);
  if (Number.isNaN(num)) return "-";
  return `¥${num.toFixed(2)}`;
};

// 获取提现列表
const fetchWithdrawalList = async () => {
  loading.value = true;
  try {
    const params = {
      customerId: searchForm.value.customerId || "",
      withdrawalNo: searchForm.value.withdrawalNo || "",
      paymentNo: searchForm.value.paymentNo || "",
      status: searchForm.value.status || "",
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
    };

    const res = await postWithAuth(
      "/internal/financial/withdrawalApply",
      params
    );
    if (res.code === 0 && res.data) {
      withdrawalList.value = Array.isArray(res.data.list) ? res.data.list : [];
      total.value = Number(res.data.total || 0);
    } else {
      withdrawalList.value = [];
      total.value = 0;
      ElMessage.error(res.message || "获取提现列表失败");
    }
  } catch (error) {
    console.error("获取提现列表失败:", error);
    ElMessage.error("获取提现列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchWithdrawalList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    customerId: "",
    withdrawalNo: "",
    paymentNo: "",
    status: "",
  };
  currentPage.value = 1;
  fetchWithdrawalList();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchWithdrawalList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchWithdrawalList();
};

// 审核通过
const approveWithdrawal = async (row: WithdrawalInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要审核通过提现申请"${row.withdrawalNo}"吗？`,
      "确认审核通过",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await postWithAuth(
      "/internal/financial/approveWithdrawal",
      {
        withdrawalNo: row.withdrawalNo,
      }
    );

    if (response.code === 0) {
      ElMessage.success("审核通过成功");
      fetchWithdrawalList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("审核通过失败:", error);
      ElMessage.error("操作失败");
    }
  }
};

// 审核拒绝
const rejectWithdrawal = (row: WithdrawalInfo) => {
  rejectForm.value.withdrawalNo = row.withdrawalNo;
  rejectForm.value.reason = "";
  rejectDialogVisible.value = true;
};

// 确认拒绝
const confirmReject = async () => {
  if (!rejectForm.value.reason.trim()) {
    ElMessage.warning("请输入拒绝原因");
    return;
  }

  try {
    const response = await postWithAuth(
      "/internal/financial/rejectWithdrawal",
      {
        withdrawalNo: rejectForm.value.withdrawalNo,
        reason: rejectForm.value.reason,
      }
    );

    if (response.code === 0) {
      ElMessage.success("审核拒绝成功");
      rejectDialogVisible.value = false;
      fetchWithdrawalList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("审核拒绝失败:", error);
    ElMessage.error("操作失败");
  }
};

// 重置拒绝表单
const resetRejectForm = () => {
  rejectForm.value = {
    withdrawalNo: "",
    reason: "",
  };
};

// 打款
const processPayment = (row: WithdrawalInfo) => {
  paymentForm.value.withdrawalNo = row.withdrawalNo;
  paymentForm.value.amount = row.amount;
  paymentForm.value.paymentNo = "";
  paymentDialogVisible.value = true;
};

// 确认打款
const confirmPayment = async () => {
  if (!paymentForm.value.paymentNo.trim()) {
    ElMessage.warning("请输入交易单号");
    return;
  }

  try {
    const response = await postWithAuth("/internal/financial/processPayment", {
      withdrawalNo: paymentForm.value.withdrawalNo,
      paymentNo: paymentForm.value.paymentNo,
    });

    if (response.code === 0) {
      ElMessage.success("打款成功");
      paymentDialogVisible.value = false;
      fetchWithdrawalList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("打款失败:", error);
    ElMessage.error("操作失败");
  }
};

// 重置打款表单
const resetPaymentForm = () => {
  paymentForm.value = {
    withdrawalNo: "",
    amount: 0,
    paymentNo: "",
  };
};

// 重新打款
const retryPayment = async (row: WithdrawalInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要重新打款"${row.withdrawalNo}"吗？`,
      "确认重新打款",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await postWithAuth("/internal/financial/retryPayment", {
      withdrawalNo: row.withdrawalNo,
    });

    if (response.code === 0) {
      ElMessage.success("重新打款成功");
      fetchWithdrawalList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("重新打款失败:", error);
      ElMessage.error("操作失败");
    }
  }
};

// 查看详情
const viewDetail = (_row: WithdrawalInfo) => {
  ElMessage.info("查看详情功能待实现");
};

onMounted(() => {
  fetchWithdrawalList();
});
</script>

<style scoped>
.withdrawal-apply {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #f3f4f6;
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 200px;
}

.status-select {
  width: 150px;
}

.withdrawal-table {
  margin: 0;
}

.amount-cell {
  text-align: right;
}

.amount-value {
  font-weight: 600;
  color: #1f2937;
}

.actual-amount {
  color: #10b981;
}

.fee-amount {
  color: #f59e0b;
}

.no-remark,
.no-auditor,
.no-audit,
.no-payment,
.no-payment-no,
.no-failure {
  color: #9ca3af;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.action-btn {
  margin: 0;
}

.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #f3f4f6;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 12px;
}
</style>
